<?php
// +----------------------------------------------------------------------
// | 双擎基础框架 [ 基于ThinkLibrary扩展 ]
// +----------------------------------------------------------------------
// | 感谢ThinkLibrary原作者Anyon的封装
// +----------------------------------------------------------------------
// | Copyright (c) 2022~2024 https://www.sqm.la All rights reserved.
// +----------------------------------------------------------------------
// | Author: rotoos <87291030@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace think\admin\service;

use think\admin\Exception;
use think\admin\extend\CodeExtend;
use think\admin\Library;
use think\admin\model\SysMenu;
use think\admin\model\SysMerchant;
use think\admin\model\SysModule;
use think\admin\model\SysRobot;
use think\admin\model\SysTenant;
use think\admin\model\SysRelation;
use think\admin\model\SysUser;
use think\admin\Service;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Session;

/**
 * 系统权限管理服务
 * Class AdminService
 * @package think\admin\service
 */
class AdminService extends Service
{
    /**
     * 自定义回调处理
     * @var array
     */
    private static $checkCallables = [];
    /**
     * 获取用户信息
     * @return array
     */
    public static function getUser(): array
    {
        if (static::isLogin()) {
            return Library::$sapp->session->get('user', []);
        } else {
            return [];
        }
    }

    /**
     * 是否已经登录
     * @return boolean
     */
    public static function isLogin(): bool
    {
        return static::getUserId() > 0;
    }

    /**
     * 获取后台用户ID
     * @return int
     */
    public static function getUserId(): int
    {
        return intval(Library::$sapp->session->get('user.id', 0));
    }

    /**
     * 获取用户是否有推送设置
     * @return false|mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getUserRobot($uid): mixed
    {
        $userId = self::isLogin() ? static::getUserId() : $uid;
        if ($userId > 0) {
            $robots = SysRobot::mk()
                ->where(['is_deleted' => 0, 'status' => 0, 'user_id' => $userId])
                ->select()
                ->toArray();

            if (!empty($robots)) {
                // 查找 isDefault === 1 的记录
                foreach ($robots as $robot) {
                    if (isset($robot['isDefault']) && $robot['isDefault'] === 1) {
                        return $robot;
                    }
                }
                // 如果没有 isDefault === 1 的记录，返回第一条
                return $robots[0];
            }
        }
        return false;
    }


    /**
     * 获取用户扩展数据
     * @param null|string $field
     * @param null|mixed $default
     * @return array|mixed
     */
    public static function getUserData(?string $field = null, $default = null)
    {
        $data = SystemService::getData('UserData_' . static::getUserId());
        return is_null($field) ? $data : ($data[$field] ?? $default);
    }

    /**
     * 设置用户扩展数据
     * @param array $data
     * @param boolean $replace
     * @return boolean
     * @throws \think\admin\Exception
     */
    public static function setUserData(array $data, bool $replace = false): bool
    {
        $data = $replace ? $data : array_merge(static::getUserData(), $data);
        return SystemService::setData('UserData_' . static::getUserId(), $data);
    }

    /**
     * 获取用户使用习惯
     * @return string
     * @throws \think\admin\Exception
     */
    public static function getUserUsageHabit(): string
    {
        $default = 'default';
        return static::getUserData('usage_habit_'. static::getUserId(), $default);
    }

    /**
     * 设置用户默认应用
     * @param int $moduleId
     * @return boolean
     * @throws Exception
     */
    public static function setUserDefaultApp(int $moduleId): bool
    {
        return static::setUserData(['default_app_'. static::getUserId() => $moduleId]);
    }

    /**
     * 获取用户默认应用
     * @return string
     * @throws \think\admin\Exception
     */
    public static function getUserDefaultApp(): int
    {
        return static::getUserData('default_app_'. static::getUserId(), null);
    }

    /**
     * 设置用户使用习惯
     * @param string $habit 使用习惯
     * @return boolean
     * @throws \think\admin\Exception
     */
    public static function setUserUsageHabit(string $habit): bool
    {
        return static::setUserData(['usage_habit_'. static::getUserId() => $habit]);
    }

    /**
     * 获取用户手机端首页快捷菜单设置
     * @return string
     * @throws \think\admin\Exception
     */
    public static function getUserShortcutMenu(): string
    {
        $default = 'default';
        return static::getUserData('shortcut_menu_'. static::getUserId(), $default);
    }

    /**
     * 设置用户手机端首页快捷菜单
     * @param string $shortcutMenu
     * @return boolean
     * @throws Exception
     */
    public static function setUserShortcutMenu(string $shortcutMenu): bool
    {
        return static::setUserData(['shortcut_menu_'. static::getUserId() => $shortcutMenu]);
    }

    /**
     * 获取租户ID
     * @return string
     */
    public static function getTenantId(): string
    {
        if(static::getUserId()>0){
            return RelationService::getUserByTenantId(static::getUserId());
        }else{
            return '-1';
        }
    }

    /**
     * 获取该用户所在租户信息
     * @param string $tenantId
     * @return array
     */
    public static function getTenant(string $tenantId): array
    {
        if(static::getUserId()>0 && $tenantId != '-1'){
            $tenant = SysTenant::mk()->where(['tenant_id' => $tenantId])->field('tenant_id,tenant_name,company_name,person_name,start_at,end_at,auth_type,auth_status')->findOrEmpty()->toArray();
            if($tenant){
                $tenant['startAt'] = date('Y-m-d',$tenant['startAt']);
                $tenant['endAt'] = date('Y-m-d',$tenant['endAt']);
            }
            return $tenant;
        }else{
            return [];
        }
    }

    /**
     * 获取商户ID
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getMerchantId(): string
    {
        if (static::getUserId() > 0) {
            $merchantId = Library::$sapp->request->param('merchantId', '');
            $merchantId = $merchantId ?: Library::$sapp->request->header('merchantId', '');
            return $merchantId ?: RelationService::getUserByMerchantId(static::getUserId());
        } else {
            return '-1';
        }
    }

    /**
     * 获取模块ID
     * @return int
     */
    public static function getModuleId(): int
    {
        if (static::getUserId() > 0) {
            $moduleId = Library::$sapp->request->param('moduleId', '');
            $moduleId = $moduleId ?: Library::$sapp->request->header('moduleId', '');
            return (int)$moduleId;
        } else {
            return 10002;
        }
    }

    /**
     * 商户code转id
     * @param $merchantCode
     * @return string
     */
    public static function merchantCodeToId($merchantCode): string
    {
        return SysMerchant::mk()->where(['merchant_code'=>$merchantCode])->where(['is_deleted'=>0])->value('merchant_id');
    }

    /**
     * 获取商户认证状态
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getMerchantStatus(): string
    {
        // 获取当前商户 ID
        $merchantId = self::getMerchantId();

        // 定义缓存键
        $cacheKey = 'merchant_status_' . $merchantId;

        // 检查 session 中是否已有缓存
        $cachedStatus = Library::$sapp->session->get($cacheKey);
        if ($cachedStatus !== null) {
            return $cachedStatus;
        }

        // 如果是配置中的商户 ID，直接返回
        if ($merchantId === config('self.merchant_id')) {
            Library::$sapp->session->set($cacheKey, 'AUTH_SUCCESS');
            return 'AUTH_SUCCESS';
        }

        // 查询数据库获取商户状态
        $authStatus = SysMerchant::mk()
            ->where(['merchant_id' => $merchantId])
            ->where(['is_deleted' => 0])
            ->value('auth_status');

        // 缓存结果到 session
        Library::$sapp->session->set($cacheKey, $authStatus);

        return $authStatus;
    }


    /**[]
     * 获取租户认证状态
     * @return string
     */
    public static function getTenantStatus(): string
    {
        // 获取当前租户 ID
        $tenantId = self::getTenantId();

        // 定义缓存键
        $cacheKey = 'tenant_status_' . $tenantId;

        // 检查 session 中是否已有缓存
        $cachedStatus = Library::$sapp->session->get($cacheKey);
        if ($cachedStatus !== null) {
            return $cachedStatus;
        }

        // 查询数据库获取租户状态
        $authStatus = SysTenant::mk()
            ->where(['tenant_id' => $tenantId])
            ->where(['is_deleted' => 0])
            ->value('auth_status');

        // 缓存结果到 session
        Library::$sapp->session->set($cacheKey, $authStatus);

        return $authStatus;
    }


    /**
     * 获取该用户所在商户信息
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getMerchantList(): array
    {
        if (static::getUserId() > 0) {
            return RelationService::getUserByMerchantList(static::getUserId());
        } else {
            return [];
        }
    }

    /**
     * 是否为平台管理员（全局管理员）
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function isGlobalAdmin(): bool
    {
        return static::getAdminType() === 100;
    }

    /**
     * 是否为租户管理员
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function isTenantAdmin(): bool
    {
        return static::getAdminType() === 200;
    }

    /**
     * 是否为商户管理员
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function isMerchantAdmin(): bool
    {
        return static::getAdminType() === 300 || static::getAdminType() === 400;
    }

    /**
     * 获取用户类型值 超管100,租户管理员200,商户管理员300
     * @param null $userType
     * @return int
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getAdminType($userType = null): int
    {
        $userId = static::getUserId();
        $userType = $userType ?? static::userType();

        if ($userId <= 0) {
            return -1;
        }

        if ($userType === 'GLOBAL') {
            return 100;
        }

        if ($userType === 'BIZ') {
            $isTenant = RelationService::isTenant($userId)[0] ?? null;
            if ($isTenant) {
                return 200;
            }
            $isMerchant = RelationService::isMerchant($userId)[0] ?? null;
            if ($isMerchant) {
                $role = RelationService::getMerchantSubRole($userId);
                return $role['code'] === 'merchantAdmin' ? 300 : 400;
            }

            return -1;
        }

        if (static::isSuper()) {
            return 1;
        }

        return -1;
    }


    /**
     * 获取登录用户的类型“GLOBAL”,"BIZ"
     * @return string
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function userType(): string
    {
        if (static::isLogin() && static::isSuper()) {
            return 'GLOBAL';
        } elseif (!static::isSuper()) {
            return RelationService::getUserByRoleType(static::getUserId());
        } else {
            return '';
        }
    }

    /**
     * 是否为超级用户
     * @return boolean
     */
    public static function isSuper(): bool
    {
        return static::getUserName() === static::getSuperName();
    }

    /**
     * 获取后台用户名称
     * @return string
     */
    public static function getUserName(): string
    {
        if (static::getUserId() > 0) {
            return Library::$sapp->session->get('user.account', '');
        } else {
            return '';
        }
    }

    /**
     * 获取超级用户账号
     * @return string
     */
    public static function getSuperName(): string
    {
        return Library::$sapp->config->get('app.super_user', 'superAdmin');
    }

    /**
     * 获取该用户菜单ID数组（角色关联菜单优先）
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getUserMenus(): array
    {
        // 获取当前用户 ID
        $userId = static::getUserId();

        // 定义缓存键
        $cacheKey = 'getUserMenus_' . $userId;

        // 检查 session 中是否已有缓存
        $cachedMenus = Library::$sapp->session->get($cacheKey);
        if ($cachedMenus !== null) {
            return $cachedMenus;
        }

        $menus = [];
        if (!static::isSuper() && !static::isGlobalAdmin()) {
            $roleIds = static::getRoles();
            if (count(str2arr($roleIds)) > 0) {
                // 角色关联菜单
                $menus = SysRelation::getTargetIds('SYS_ROLE_HAS_RESOURCE', $roleIds);
            } else {
                // 用户关联菜单
                $menus = SysRelation::getTargetIds('SYS_USER_HAS_RESOURCE', (string)$userId);
            }
        }

        // 查询拥有权限的菜单ID集合的上级ID数组
        $menuIds = SysMenu::getIds('id', implode(',', $menus), 'parent_id');
        // 得到上级ID集合
        $parentIds = array_unique($menuIds);
        // 合并上级ID与菜单ID
        $allMenus = array_merge($parentIds, $menus);

        // 缓存结果到 session
        Library::$sapp->session->set($cacheKey, $allMenus);

        return $allMenus;
    }

    /*public static function getUserMenus(): array
    {
        $menus = [];
        if (!static::isSuper() && !static::isGlobalAdmin()) {
            $roleIds = static::getRoles();
            if (count(str2arr($roleIds)) > 0) {
                // 角色关联菜单
                $menus = SysRelation::getTargetIds('SYS_ROLE_HAS_RESOURCE', $roleIds);
            } else {
                // 用户关联菜单
                $menus = SysRelation::getTargetIds('SYS_USER_HAS_RESOURCE', (string)static::getUserId());
            }
        }
        // 查询拥有权限的菜单ID集合的上级ID数组
        $menuIds = SysMenu::getIds('id', implode(',', $menus), 'parent_id');
        // 得到上级ID集合
        $parentIds = array_unique($menuIds);
        // 合并上级ID与菜单ID
        return array_merge($parentIds, $menus);
    }*/


    /**
     * 获取该用户的角色集
     * @return string
     */
    public static function getRoles(): string
    {
        // 获取当前用户 ID
        $userId = static::getUserId();

        // 定义缓存键
        $cacheKey = 'user_roles_' . $userId;

        // 检查 session 中是否已有缓存
        $cachedRoles = Library::$sapp->session->get($cacheKey);
        if ($cachedRoles !== null) {
            return $cachedRoles;
        }

        $roleIds = '';
        if ($userId > 0) {
            // 用户关联角色，获取该用户所有角色ID
            $roleIdsArray = SysRelation::getTargetIds('SYS_USER_HAS_ROLE', (string)$userId);
            if (!$roleIdsArray) {
                $roleIdsArray = SysRelation::getObjectIds('SYS_ROLE_HAS_USER', (string)$userId);
            }
            $roleIds = $roleIdsArray ? implode(',', $roleIdsArray) : '';
        }

        // 缓存结果到 session
        Library::$sapp->session->set($cacheKey, $roleIds);

        return $roleIds;
    }

    /*public static function getRoles(): string
    {
        $userId = static::getUserId();
        if ($userId > 0) {
            // 用户关联角色，获取该用户所有角色id
            $roleIds = SysRelation::getTargetIds('SYS_USER_HAS_ROLE', (string)$userId);
            if (!$roleIds) {
                $roleIds = SysRelation::getObjectIds('SYS_ROLE_HAS_USER', (string)$userId);
            }
            return $roleIds ? implode(',', $roleIds) : '';
        }
        return '';
    }*/

    /**
     * 注册权限检查函数
     * @param callable $callable
     * @return integer
     */
    public static function registerCheckCallable(callable $callable): int
    {
        self::$checkCallables[] = $callable;
        return count(self::$checkCallables) - 1;
    }

    /**
     * 移除权限检查函数
     * @param ?integer $index
     * @return boolean
     */
    public static function removeCheckCallable(?int $index): bool
    {
        if (is_null($index)) {
            self::$checkCallables = [];
            return true;
        } elseif (isset(self::$checkCallables[$index])) {
            unset(self::$checkCallables[$index]);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查指定节点授权
     * @param string|null $node
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws \ReflectionException
     */
    public static function check(?string $node = ''): bool
    {
        $skey1 = 'think-library-methods';
        $current = NodeService::fullNode($node);
        $methods = sysvar($skey1) ?: sysvar($skey1, NodeService::getMethods());
        $usernodes = Library::$sapp->session->get('user.nodes', []);
        // 自定义权限检查回调
        if (count(self::$checkCallables) > 0) {
            foreach (self::$checkCallables as $callable) {
                if ($callable($current, $methods, $usernodes) === false) {
                    return false;
                }
            }
            return true;
        }
        // 自定义权限检查方法
        if (function_exists('admin_check_filter')) {
            return call_user_func('admin_check_filter', $current, $methods, $usernodes);
        }
        // 超级用户不需要检查权限
        if (static::isSuper() || static::isGlobalAdmin()) return true;
        // 节点权限检查，需要兼容 windows 控制器不区分大小写，统一去除节点下划线再检查权限
        if (empty($simples = sysvar($skey2 = 'think-library-method-simples') ?: [])) {
            foreach ($methods as $k => $v) $simples[strtr($k, ['_' => ''])] = $v;
            sysvar($skey2, $simples);
        }
        if (empty($simples[$simple = strtr($current, ['_' => ''])]['isauth'])) {
            return !(!empty($simples[$simple]['islogin']) && !static::isLogin());
        } else {
            return in_array($current, $usernodes);
        }
    }

    /**
     * 初始化用户权限在用户登录时刷新权限
     * @param bool $force
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function apply(bool $force = false): array
    {
        if ($force) {
            static::clear();
        }

        $userId = static::getUserId();
        if ($userId <= 0) {
            return [];
        }

        $user = static::getUser();
        if (!empty($user['loginNum'])) {
            unset($user['loginNum']);
        }

        // 设置默认头像
        $user['avatar'] = $user['avatar'] ?? '';

        $user['tenantId'] = static::getTenantId();
        $user['tenant'] = static::getTenant($user['tenantId']);
        $user['merchant'] = static::getMerchant();

        $merchantDetail = $user['merchant']['self'] ? static::getMerchantDetail($user['merchant']['self']) : [];
        $roleCode = static::getRoleCode();

        $user['roleCode'] = $roleCode['code'];
        $user['roleName'] = $roleCode['name'];
        $user['authStatus'] = $merchantDetail['authStatus'] ?? 'NOT_AUTH';
        $user['infoType'] = $merchantDetail['infoType'] ?? 'NORMAL';
        $user['module'] = static::getMerchantModule($merchantDetail);

        // 获取用户角色
        $roles = static::getRoles();
        // 获取用户节点
        $user['nodes'] = static::getUserNodes($userId, $roles);

        Library::$sapp->session->set('user', $user);
        return $user;
    }

    /**
     * @param int $userId
     * @param string $roles
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private static function getUserNodes(int $userId, string $roles): array
    {
        $nodes = [];

        if (!static::isSuper() && !static::isGlobalAdmin()) {
            $roleArray = str2arr($roles);
            $objectIds = count($roleArray) > 0 ? $roleArray : [$userId];
            $category = count($roleArray) > 0 ? 'SYS_ROLE_HAS_RESOURCE' : 'SYS_USER_HAS_RESOURCE';

            $resources = SysRelation::mk()
                ->where(['category' => $category])
                ->whereIn('object_id', $objectIds)
                ->select()
                ->toArray();

            $menuIds = [];
            $buttonIds = [];

            foreach ($resources as $v) {
                $menuIds[$v['targetId']] = true;
                $extJson = json_decode($v['extJson'], true);
                if (!empty($extJson['buttonInfo'])) {
                    foreach ($extJson['buttonInfo'] as $buttonId) {
                        $buttonIds[$buttonId] = true;
                    }
                }
            }

            $targetIds = array_merge(array_keys($menuIds), array_keys($buttonIds));

            if ($targetIds) {
                foreach (array_chunk($targetIds, 200) as $batch) {
                    $nodes = array_merge($nodes, SysMenu::mk()->whereIn('id', $batch)->column('code'));
                }
            }

            $nodes = array_unique($nodes);
            sort($nodes);
            foreach ($nodes as &$node) {
                $node = NodeService::fullNode($node);
            }
        }

        return $nodes;
    }

    /*public static function apply(bool $force = false): array
    {
        if ($force) {
            static::clear();
        }
        $user = [];
        $userId = static::getUserId();
        if ($userId <= 0) {
            return $user;
        }

        $user = static::getUser();
        if(!empty($user) && isset($user['loginNum'])){
            unset($user['loginNum']);
        }
        if (!isset($user['avatar']) || $user['avatar']=='') {
            $user['avatar'] = '';
        }

        $user['nodes'] = [];
        $user['tenantId'] = static::getTenantId();
        $user['tenant'] = static::getTenant($user['tenantId']);
        $user['merchant'] = static::getMerchant();
        $merchantDetail = $user['merchant']['self'] ? static::getMerchantDetail($user['merchant']['self']) : [];

        $roleCode = static::getRoleCode();
        $user['roleCode'] = $roleCode['code'];
        $user['roleName'] = $roleCode['name'];

        $user['authStatus'] = !empty($merchantDetail) ? $merchantDetail['authStatus'] : 'NOT_AUTH';
        $user['infoType'] = !empty($merchantDetail) ? $merchantDetail['infoType'] : 'NORMAL';
        $user['module'] = static::getMerchantModule($merchantDetail);
        $roles = static::getRoles();

        if (!static::isSuper() && !static::isGlobalAdmin()) {
            $roleArray = str2arr($roles);
            $isRoleBased = count($roleArray) > 0;
            $objectIds = $isRoleBased ? $roleArray : [$userId];
            $category = $isRoleBased ? 'SYS_ROLE_HAS_RESOURCE' : 'SYS_USER_HAS_RESOURCE';

            $resources = SysRelation::mk()
                ->where(['category' => $category])
                ->whereIn('object_id', $objectIds)
                ->select()
                ->toArray();

            $menuIds = [];
            $buttonIds = [];
            foreach ($resources as $v) {
                $menuIds[$v['targetId']] = true;
                $extJson = json_decode($v['extJson'], true);
                if (!empty($extJson['buttonInfo'])) {
                    foreach ($extJson['buttonInfo'] as $buttonId) {
                        $buttonIds[$buttonId] = true;
                    }
                }
            }

            $targetIds = array_merge(array_keys($menuIds), array_keys($buttonIds));

            if ($targetIds) {
                $batchSize = 200;
                foreach (array_chunk($targetIds, $batchSize) as $batch) {
                    $user['nodes'] = array_merge($user['nodes'], SysMenu::mk()->whereIn('id', $batch)->column('code'));
                }
            }

            $user['nodes'] = array_unique($user['nodes']);
            sort($user['nodes']);
            foreach ($user['nodes'] as &$v) {
                $v = NodeService::fullNode($v);
            }
        }

        Library::$sapp->session->set('user', $user);
        return $user;
    }*/


    /**
     * 清理节点缓存
     * @return bool
     */
    public static function clear(): bool
    {
        Library::$sapp->cache->delete('SystemAuthNode');
        return true;
    }

    /**
     * 获取商户可以使用的模块
     * @param $merchant
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getMerchantModule($merchant): array
    {
        // 如果用户ID小于或等于0，直接返回空数组
        if (static::getUserId() <= 0) {
            return [];
        }
        // 商户信息不存在
        if (!$merchant) {
            return [];
        }

        $module = $merchant['subName'] ? explode(',',$merchant['subName']) : [];

        if(empty($module)) {
            return [];
        }
        return SysModule::mk()->whereIn('id',$module)->where(['is_deleted' => 0,'status'=>0])->select()->toArray();
    }

    /**
     * 获取该用户所在商户信息
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getMerchant(): array
    {
        $userId = static::getUserId();
        if ($userId > 0) {
            return RelationService::getUserByMerchant($userId);
        }
        return [];
    }

    /**
     * 获取用户账号类型
     * @return array|string[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public static function getRoleCode(): array
    {
        // 如果用户ID小于或等于0，直接返回空数组
        if (static::getUserId() <= 0) {
            return [];
        }

        // 超级管理员的情况
        if (static::isSuper() || static::isGlobalAdmin()) {
            return ['code' => 'superAdmin', 'name' => '平台超级管理员'];
        }

        // 根据用户类型返回相应的角色
        $userType = static::getAdminType();
        return match ($userType) {
            100 => ['code' => 'globalAdmin', 'name' => '全局管理员'],
            200 => ['code' => 'tenantAdmin', 'name' => '租户管理员'],
            300 => ['code' => 'merchantAdmin', 'name' => '商户管理员'],
            default => ['code' => 'ordinaryAdmin', 'name' => '普通管理员'],
        };
    }


    /**
     * 获取租户认证信息
     * @param string $tenantId
     * @return string
     */
    public static function getTenantAuthStatus(string $tenantId): string
    {
        if (!$tenantId) {
            return 'NOT_AUTH';
        }
        $auth = SysTenant::mk()->where(['tenant_id' => $tenantId])->value('auth_status');
        return $auth ? $auth : 'NOT_AUTH';
    }

    /**
     * 获取商户认证信息
     * @param string $merchantId
     * @return string
     */
    public static function getMerchantAuthStatus(string $merchantId): string
    {
        if (!$merchantId) {
            return 'NOT_AUTH';
        }
        $auth = SysMerchant::mk()->where(['merchant_id' => $merchantId])->value('auth_status');
        return $auth ? $auth : 'NOT_AUTH';
    }

    /**
     * 获取商户详情
     * @param string $merchantId
     * @return array
     */
    public static function getMerchantDetail(string $merchantId): array
    {
        if (!$merchantId) {
            return [];
        }
        return SysMerchant::mk()->where(['merchant_id' => $merchantId])->where(['is_deleted'=>0,'status'=>0])->findOrEmpty()->toArray();
    }

    /**
     * 获取商户信息规范
     * @param string $merchantId
     * @return string
     */
    public static function getMerchantInfoType(string $merchantId): string
    {
        if (!$merchantId) {
            return 'NORMAL';
        }
        $info = SysMerchant::mk()->where(['merchant_id' => $merchantId])->value('info_type');
        return $info ? $info : 'NORMAL';
    }

    /**
     * 获取会员上传配置
     * @param ?string $uptoken
     * @return array [unid,exts]
     */
    public static function withUploadUnid(?string $uptoken = null): array
    {
        try {
            if ($uptoken === '') return [0, []];
            $session = Library::$sapp->session;
            if (is_null($uptoken)) {
                $sesskey = $session->get('UploadSessionKey');
                if (empty($sesskey)) return [0, []];
                if ($session->getId() !== $sesskey) {
                    $session = Library::$sapp->invokeClass(Session::class);
                    $session->setId($sesskey);
                    $session->init();
                }
                $unid = intval($session->get('AdminUploadUnid', 0));
            } else {
                $sesskey = CodeExtend::decrypt($uptoken, sysconfig('OTHER','SQM_JWT_BASE_KEY'));
                if (empty($sesskey)) return [0, []];
                if ($session->getId() !== $sesskey) {
                    $session = Library::$sapp->invokeClass(Session::class);
                    $session->setId($sesskey);
                    $session->init();
                }
                if ($unid = intval($session->get('AdminUploadUnid', 0))) {
                    $session->set('UploadSessionKey', $session->getId());
                }
            }
            return [$unid, $session->get('AdminUploadExts', [])];
        } catch (\Error|\Exception $exception) {
            return [0, []];
        }
    }

    /**
     * 生成上传入口令牌
     * @param integer $unid 会员编号
     * @param string $exts 允许后缀(多个以英文逗号隔开)
     * @return string
     * @throws \think\admin\Exception
     */
    public static function withUploadToken(int $unid, string $exts = ''): string
    {
        Library::$sapp->session->set('AdminUploadUnid', $unid);
        Library::$sapp->session->set('AdminUploadExts', str2arr(strtolower($exts)));
        return CodeExtend::encrypt(Library::$sapp->session->getId(), sysconfig('OTHER','SQM_JWT_BASE_KEY'));
    }

    /**
     * 静态方法兼容(临时)
     * @param string $method
     * @param array $arguments
     * @return bool
     * @throws \think\admin\Exception
     */
    public static function __callStatic(string $method, array $arguments)
    {
        if (strtolower($method) === 'clearcache') return static::clear();
        throw new Exception("method not exists: AdminService::{$method}()");
    }

    /**
     * 对象方法兼容(临时)
     * @param string $method
     * @param array $arguments
     * @return bool
     * @throws \think\admin\Exception
     */
    public function __call(string $method, array $arguments)
    {
        return static::__callStatic($method, $arguments);
    }
}